<template>
	<div class="content">
		<!-- 页面头部 -->
		<div class="page-header">
			<button class="back-btn" @click="goBack">← 返回</button>
			<div class="page-title">席位详情</div>
		</div>

		<!-- 席位信息 -->
		<div class="seat-info-section">
			<div class="card">
				<div class="card-header">
					<div class="title">席位信息</div>
					<div class="seat-status" :class="getStatusClass(seatInfo.status)">
						{{ getStatusText(seatInfo.status) }}
					</div>
				</div>
				<div v-if="loading" class="loading-container">
					<div class="loading-spinner"></div>
					<text>加载中...</text>
				</div>
				<div v-else class="info-content">
					<div class="info-row">
						<div class="info-label">席位ID:</div>
						<div class="info-value">{{ seatInfo.id || '未知' }}</div>
					</div>
					<div class="info-row">
						<div class="info-label">席位所有者:</div>
						<div class="info-value">{{ seatInfo.owner || '未分配' }}</div>
					</div>
				
				</div>
			</div>
		</div>

		<!-- 房间规则 -->
		<div class="room-rules-section" v-if="roomRules.length > 0">
			<div class="card">
				
				<div v-if="ruleLoading" class="loading-container">
					<div class="loading-spinner"></div>
					<text>加载规则中...</text>
				</div>
				<div v-else class="rules-content">
		
					<!-- 规则列表 -->
					<div class="rules-list">
						<div class="rules-title">所有回合</div>
						<div 
							class="rule-item" 
							v-for="(rule, index) in roomRules" 
							:key="rule.id"
							:class="{ 
								'current': index === currentRuleIndex, 
								'completed': completedRules.has(index) 
							}"
						>
							<div class="rule-number">{{ index + 1 }}</div>
							<div class="rule-content">
								<div class="rule-path">{{ rule.startPoint }} → {{ rule.endPoint }}</div>
								<div class="rule-meta">
									<span class="meta-item">准备: {{ rule.prepareTime ? rule.prepareTime / 1000 + 's' : '无限制' }}</span>
									<span class="meta-item">限制: {{ rule.limitTime ? rule.limitTime / 1000 + 's' : '无限制' }}</span>
									<span class="meta-item">计分: {{ getScoreModelText(rule.scoreModel) }}</span>
									<span class="meta-item">对战: {{ getBattleModelText(rule.battleModel) }}</span>
								</div>
							</div>
							<div class="rule-status">
								<span v-if="completedRules.has(index)" class="status-completed">已完成</span>
								<span v-else-if="index === currentRuleIndex" class="status-current">进行中</span>
								<span v-else class="status-pending">待执行</span>
							</div>
						</div>
					</div>
					
					<!-- 规则控制按钮 -->
					<div class="rule-controls" v-if="roomRules.length > 1">
						<button class="control-btn" @click="resetRuleExecution" :disabled="currentRuleIndex === 0">
							重置规则
						</button>
						<button class="control-btn" @click="startNextRule" :disabled="currentRuleIndex >= roomRules.length - 1">
							下一回合
						</button>
					</div>
				</div>
			</div>
		</div>

		<div class="main">
		

			<div class="card flex">
				<div class="title">连接魔方：</div>
				<button @click="bleShowScan">连接设备</button>
				<button @click="bleDisconnect">断开设备</button>
			</div>
			
			<div class="card">
				<div class="title">设备信息：</div>
				<code>
					<template v-if="equipment.length">
						设备名：{{ equipment.filter(v => v.model)[0]?.model }},
						版本：{{ equipment.filter(v => v.version)[0]?.version }}
						电量：{{ battery.batteryPower }}
					</template>
				</code>
			</div>
			
			<div class="card flex blank">
				<div class="title">重置魔方至复原状态：</div>
				<button @click="cubeReset">重置魔方</button>
			</div>
			
			<!-- 开始比赛按钮 -->
			<div class="card start-game flex" v-if="[0, 4].includes(timeStore.stage)">
				<div class="title">点击开始打乱：</div>
				<button @click="start" v-if="timeStore.stage === 0">开始比赛</button>
				<button @click="start" v-if="timeStore.stage === 4">再次挑战</button>
			</div>
			
			
			<!-- 打乱阶段 -->
			<div class="card formulaDisplay blank" v-if="timeStore.stage === 1">
				<div class="timer">
					打乱中 <span class="led">{{ times }}</span>
				</div>
				<FormulaDisplay class="formula-display" v-if="cube_generate_scramble" :formula="cube_generate_scramble"
					@on-done-scramble="onDoneScramble" @on-stop-scramble="onStopScramble" @on-error-count-max="onErrorMax" />
				<button class="btn" color="linear-gradient(299.95deg, #009AFF 23.55%, #00C7FD 78.39%)"
					@click="onGiveUp">放弃</button>
			</div>

			<!-- 观察阶段 -->
			<div class="card blank" v-if="timeStore.stage === 2">
				<div class="timer fixed">
					观察中
					<span class="led">{{ times }}</span>

					<button class="btn" color="linear-gradient(299.95deg, #009AFF 23.55%, #00C7FD 78.39%)"
						@click="onGiveUp">放弃</button>
				</div>
			</div>

			<!-- 复原阶段 -->
			<div class="card blank" v-if="timeStore.stage === 3">
				<div class="timer">
					复原中
					<p class="led">
						{{ formatTime(times) }}
					</p>

					<button class="btn" color="linear-gradient(299.95deg, #009AFF 23.55%, #00C7FD 78.39%)"
						@click="onGiveUp">放弃</button>
				</div>
			</div>

			<!-- 结果阶段 -->
			<div class="card blank result" v-if="timeStore.stage === 4">
				<div class="timer">
					结果
					<p class="msg">
						{{ formatTime(timeStore.gameTime) }}
					</p>

					<div class="msg">步数：{{ timeStore.turn }}</div>
					<div class="msg">TPS：{{ timeStore.tps }}</div>
				</div>
			</div>

			<!-- 历史记录 -->
			<div class="card blank">
				<div class="race-box blank" v-for="item in timeStore.result" :key="item.iStartTime">
					<div class="title">第{{ item.mRecord.iSession }}场</div>
					<code>
						<p>结束时间：{{ formatDate(item.mRecord.iEndTime) }}</p>
						<p>复原用时：{{ formatTime(item.mRecord.mData.iDuration) }}</p>
						<p>步数：{{ item.mRecord.mData.iTurn }}</p>
						<p>TPS：{{ item.mRecord.mData.sTPS }}</p>
						<p>打乱公式：{{ item.mRecord.mData.sScramble }}</p>
						<p>复原步骤：{{ item.mRecord.mData.sReduction }}</p>
					</code>
				</div>
			</div>
	
			<div class="viewBox">
				<div class="card cube-box">
					<div class="cube3d"></div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
	} from 'vue';
	import { onLoad } from '@dcloudio/uni-app'

	import {
		mCall,
		mBus
	} from '@/utils/mCall.js'
	import {
		CubeMap,
		formatTime,
		formatDate,
		mergeMove,
	} from '@/utils/common.js'
	import {
		useCubeStore
	} from "@/stores/cube";
	import {
		useTimeStore
	} from "@/stores/time";
	import {
		useUserStore
	} from "@/stores/user";
	import cube3d from '@/utils/cube3d.js'
	import { MatchRoomSeatAPI, BattleAPI, MatchRoomRuleAPI, MatchRoomResultAPI } from '@/api/battle.js'
	import Cube from '@/utils/cube.js'
	import FormulaDisplay from "@/components/FormulaDisplay.vue";
	import vmCube from '@/utils/solve.js'
	import SocketServerAdapter from '@/utils/socketServerAdapter.js'
	import globalWebSocket from '@/utils/globalWebSocket.js'

	const cubeStore = useCubeStore();
	const timeStore = useTimeStore();
	const userStore = useUserStore();

	const VmCube = new vmCube()

	// 页面参数
	const seatId = ref('')
	const seatInfo = ref({})
	const loading = ref(false)
	
	// 房间规则相关
	const roomRules = ref([])
	const currentRuleIndex = ref(0)
	const ruleLoading = ref(false)
	const completedRules = ref(new Set()) // 跟踪已完成的规则

	//是否有蓝牙权限
	const ble_has_permission = ref(false)
	//设备是否已连接
	const ble_is_connected = ref(false)
	//生成的打乱规则
	const cube_generate_scramble = ref('')
	//当前转动的字母代号
	const cubeMoves = ref([])
	// 设备信息
	const equipment = ref([])
	// 电池信息
	const battery = ref({})

	const times = ref(45);
	const moved = ref(false)

	let intervalTimer = undefined
	let watchCompleted = null
	let wait = 0
	let waitTime = 1000
	let cubeGame = null
	let faceLetsTime = 0

	const socketAdapter = ref(null)
	const connected = ref(false)

	// 初始化Socket适配器
	const initSocketAdapter = async () => {
		try {
			console.log('开始初始化WebSocket连接...')
			console.log('全局WebSocket连接状态:', globalWebSocket.getConnectionStatus())
			console.log('全局WebSocket是否已连接:', globalWebSocket.isConnected())
			
			// 只获取全局WebSocket实例，不再connect
			socketAdapter.value = await globalWebSocket.getConnection()
			connected.value = globalWebSocket.isConnected()
			console.log('使用全局WebSocket连接，连接状态:', connected.value)
			console.log('socketAdapter.value:', socketAdapter.value)
			
			if (socketAdapter.value && connected.value) {
				console.log('WebSocket连接成功，可以发送消息')
				
				// 监听魔方转动广播
				socketAdapter.value.on('player_cube_move', (data) => {
					console.log('收到魔方转动广播:', data)
					// 处理魔方转动广播数据
					if (data.code === 1 && data.move) {
						console.log(`收到其他玩家的魔方转动: ${data.move}, 间隔: ${data.interval}, 步数: ${data.step}, 角度: ${data.rotate}`)
						// 这里可以添加处理其他玩家魔方转动的逻辑
						// 比如更新UI显示、播放音效等
					}
				})
				
				// 监听房间状态变更
				socketAdapter.value.on('room_status_change', (data) => {
					console.log('收到房间状态变更:', data)
					// 处理房间状态变更
				})
				
				// 监听席位状态变更
				socketAdapter.value.on('room_seat_status_change', (data) => {
					console.log('收到席位状态变更:', data)
					// 处理席位状态变更
				})
				
				// 监听成绩上报响应
				socketAdapter.value.on('room_seat_owner_status_change', (data) => {
					console.log('收到成绩上报响应:', data)
					// 处理成绩上报响应
				})
			} else {
				console.warn('WebSocket连接失败或未连接')
			}
		} catch (error) {
			console.error('获取WebSocket连接失败:', error)
			connected.value = false
			socketAdapter.value = null
		}
	}

	// 席位状态映射
	const statusMap = {
		0: '空闲',
		1: '占用',
		2: '准备-等待比赛开始',
		3: '赛前准备',
		4: '策略规划',
		5: '比赛',
		6: '比赛结束',
		99: '异常'
	}

	const statusClassMap = {
		0: 'status-idle',
		1: 'status-occupy',
		2: 'status-ready',
		3: 'status-prepare',
		4: 'status-plan',
		5: 'status-matching',
		6: 'status-end',
		99: 'status-error'
	}

	const eventMap = {
		0: '加入',
		1: '准备',
		2: '开始赛前准备',
		3: '策略规划',
		4: '开始比赛',
		5: '结束比赛',
		6: '离开',
		7: '发生异常',
		8: '重新开始比赛'
	}

	const roleMap = {
		1: '房间创建权限',
		2: '房间删除权限',
		3: '房间设置更新权限',
		4: '开始游戏权限',
		5: '暂停游戏权限',
		6: '结束游戏权限',
		7: '回合开始权限',
		8: '回合结束权限',
		9: '加入房间/席位权限',
		10: '踢出玩家权限',
		11: '玩家准备权限',
		12: '裁判验证权限',
		13: '裁判处罚权限',
		14: '观众加入权限',
		15: '观众离开权限',
		17: '游戏错误权限',
		18: '取消游戏权限',
		19: '恢复游戏权限',
		20: '游戏准备权限',
		21: '游戏策略规划权限'
	}

	// 工具函数
	const getStatusText = (status) => statusMap[status] || '未知'
	const getStatusClass = (status) => statusClassMap[status] || 'status-unknown'
	const getEventText = (event) => eventMap[event] || '未知'
	const getRoleText = (role) => roleMap[role] || '未知'
	
	// 获取计分模式文本
	const getScoreModelText = (scoreModel) => {
		const scoreModelMap = {
			0: '不记分',
			1: '时间短',
			2: '时间长',
			3: '距离短',
			4: '距离长',
			5: '得分少',
			6: '得分多',
			7: '步数短',
			8: '步数长'
		}
		return scoreModelMap[scoreModel] || '未知'
	}
	
	// 获取对战模式文本
	const getBattleModelText = (battleModel) => {
		const battleModelMap = {
			0: '接力',
			1: '单回合',
			2: '多回合'
		}
		return battleModelMap[battleModel] || '未知'
	}

	// 获取席位信息
	const fetchSeatInfo = async () => {
		if (!seatId.value) return
		
		loading.value = true
		try {
			console.log('获取席位信息，席位ID:', seatId.value)
			
			// 使用更精确的查询方式
			const result = await MatchRoomSeatAPI.page({
				matchRoomSeatId: seatId.value,
				pageNum: 0,
				pageSize: 100
			})
			
			console.log('席位信息API返回结果:', result)
			
			if (result.code === 0 && result.data) {
				// 从分页结果中查找指定席位ID的数据
				const seatList = result.data.list || result.data || []
				const targetSeat = seatList.find(seat => 
					seat.id === seatId.value || 
					seat.matchRoomSeatId === seatId.value ||
					seat.matchRoomSeatId === seatId.value
				)
				
				if (targetSeat) {
					seatInfo.value = targetSeat
					console.log('获取到席位信息:', seatInfo.value)
					
					// 获取房间规则
					if (targetSeat.matchRoomId) {
						fetchRoomRules(targetSeat.matchRoomId)
					} else {
						console.log('席位信息中没有房间ID，尝试通过其他方式获取')
						// 如果没有房间ID，可以尝试通过其他方式获取
						// 比如通过席位ID查询房间信息
					}
				} else {
					// 如果精确查询没有结果，尝试模糊查询
					const fuzzyResult = await MatchRoomSeatAPI.page({
						pageNum: 0,
						pageSize: 100
					})
					
					if (fuzzyResult.code === 0 && fuzzyResult.data) {
						const allSeats = fuzzyResult.data.list || fuzzyResult.data || []
						const foundSeat = allSeats.find(seat => 
							seat.id === seatId.value || 
							seat.matchRoomSeatId === seatId.value
						)
						
						if (foundSeat) {
							seatInfo.value = foundSeat
							console.log('通过模糊查询获取到席位信息:', seatInfo.value)
							
							if (foundSeat.matchRoomId) {
								fetchRoomRules(foundSeat.matchRoomId)
							}
						} else {
							throw new Error('未找到指定的席位信息')
						}
					} else {
						throw new Error('未找到指定的席位信息')
					}
				}
			} else {
				throw new Error(result.msg || '获取席位信息失败')
			}
		} catch (error) {
			console.error('获取席位信息失败:', error)
			uni.showToast({
				title: error.message || '获取席位信息失败',
				icon: 'none'
			})
			
			// 如果获取失败，使用默认数据
			seatInfo.value = {
				id: seatId.value,
				owner: '获取失败',
				role: 0,
				status: 99,
				event: 0,
				signTime: null,
				createTime: null
			}
		} finally {
			loading.value = false
		}
	}

	// 获取房间规则
	const fetchRoomRules = async (roomId) => {
		if (!roomId) return
		
		ruleLoading.value = true
		try {
			console.log('获取房间规则，房间ID:', roomId)
			const result = await MatchRoomRuleAPI.page({
				matchRoomId: roomId,
				pageNum: 0,
				pageSize: 100
			})
			
			console.log('房间规则API返回结果:', result)
			
			if (result.code === 0 && result.data) {
				const ruleList = result.data.list || result.data || []
				// 按照sort字段排序
				roomRules.value = ruleList.sort((a, b) => (a.sort || 0) - (b.sort || 0))
				console.log('获取到房间规则:', roomRules.value)
			} else {
				roomRules.value = []
				console.log('该房间暂无规则')
			}
		} catch (error) {
			console.error('获取房间规则失败:', error)
			roomRules.value = []
		} finally {
			ruleLoading.value = false
		}
	}

	// 获取当前规则
	const getCurrentRule = () => {
		if (roomRules.value.length === 0 || currentRuleIndex.value >= roomRules.value.length) {
			return null
		}
		return roomRules.value[currentRuleIndex.value]
	}

	// 获取规则文本描述
	const getRuleDescription = (rule) => {
		if (!rule) return ''
		
		const scoreModelMap = {
			0: '不记分',
			1: '时间短',
			2: '时间长',
			3: '距离短',
			4: '距离长',
			5: '得分少',
			6: '得分多',
			7: '步数短',
			8: '步数长'
		}
		
		const battleModelMap = {
			0: '接力',
			1: '单回合',
			2: '多回合'
		}
		
		const prepareTimeText = rule.prepareTime ? `${rule.prepareTime / 1000}秒` : '无限制'
		const limitTimeText = rule.limitTime ? `${rule.limitTime / 1000}秒` : '无限制'
		
		return `${rule.startPoint} → ${rule.endPoint} | 准备: ${prepareTimeText} | 限制: ${limitTimeText} | 计分: ${scoreModelMap[rule.scoreModel] || '未知'} | 对战: ${battleModelMap[rule.battleModel] || '未知'}`
	}

	// 开始下一个规则
	const startNextRule = () => {
		if (currentRuleIndex.value < roomRules.value.length - 1) {
			// 确认是否要开始下一回合
			uni.showModal({
				title: '开始下一回合',
				content: `确定要开始第 ${currentRuleIndex.value + 2} 回合吗？`,
				success: (res) => {
					if (res.confirm) {
						currentRuleIndex.value++
						console.log(`开始执行第 ${currentRuleIndex.value + 1} 个规则:`, getCurrentRule())
						
						// 重置比赛状态
						timeStore.reset()
						cubeStore.moveList = []
						cubeStore.moveTimeList = []
						cubeMoves.value = []
						
						// 重置魔方状态
						cubeReset()
						
						// 自动开始下一回合的比赛
						setTimeout(() => {
							start()
						}, 1000) // 1秒后开始下一回合
					}
				}
			})
		} else {
			console.log('所有规则执行完成')
			uni.showToast({
				title: '所有回合已完成！',
				icon: 'success'
			})
		}
	}

	// 重置规则执行
	const resetRuleExecution = () => {
		uni.showModal({
			title: '重置规则执行',
			content: '确定要重置到第一回合吗？这将清除所有比赛进度。',
			success: (res) => {
				if (res.confirm) {
					currentRuleIndex.value = 0
					completedRules.value.clear() // 清空已完成的规则记录
					console.log('重置规则执行')
					
					// 重置比赛状态
					timeStore.reset()
					cubeStore.moveList = []
					cubeStore.moveTimeList = []
					cubeMoves.value = []
					
					// 重置魔方状态
					cubeReset()
					
					// 更新席位状态为准备状态
					updateSeatStatus(0, 0)
					
					uni.showToast({
						title: '已重置到第一回合',
						icon: 'success'
					})
				}
			}
		})
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}

	// 打开蓝牙连接面板
	const bleShowScan = () => {
		mCall('ble_show_scan')
		
		equipment.value = []
		if (!equipment.value.length) {
			const inter = setInterval(() => {
				if (equipment.value.length) {
					clearInterval(inter)
				} else {
					getEquipment()
					getBattery()
				}
			}, 5000)
		}
	}

	// 断开魔方连接
	const bleDisconnect = () => {
		mCall('ble_disconnect', '')
	}

	// 魔方复原重置
	const cubeReset = () => {
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 6,
				step: 1,
				count: 28,
			}
		})
	
		if (cubeGame) {
			cubeGame.facelets.setFaceLets('UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB')
			cubeGame.cube.reset()
		}
		
		VmCube.identity()
		
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 3,
				step: 1,
				count: 28,
			}
		})
	}

	// 开始游戏
	const beginGame = () => {
//		mCall('cube_generate_scramble')
	}

	// 放弃
	const onGiveUp = () => {
		timeStore.endScramble();
		timeStore.giveUp();
		timeStore.checkout(
			cubeStore.moveList,
			cubeStore.moveTimeList,
			cubeStore.model
		);
		clearInterval(intervalTimer);
		intervalTimer = undefined;
		// 阶段0（准备）
		updateSeatStatus(0, 0)
		timeStore.reset()
	}

	//打乱结束
	const onStopScramble = () => {
		timeStore.endScramble();
		uni.showToast({
			title: '打乱未完成,请重新开始',
			icon: 'none'
		})
		timeStore.reset()
		clearInterval(intervalTimer);
	};

	//开始观察
	const onDoneScramble = () => {
		timeStore.endScramble();
		// 阶段2（观察/策略规划）
		updateSeatStatus(4, 3)
		observe();
	};

	const onErrorMax = () => {
		timeStore.endScramble();
		uni.showToast({
			title: '打乱失败,请重新开始',
			icon: 'none'
		})
		timeStore.reset()
		clearInterval(intervalTimer);
	};

	// 观察模块
	const observe = () => {
		times.value = 15

		clearInterval(intervalTimer)
		intervalTimer = setInterval(() => {
			times.value--
			if (times.value <= 0) {
				times.value = 0
			}
			if (times.value <= 0) {
				clearInterval(intervalTimer)
				intervalTimer = undefined
				onStopWatch()
			}
		}, 1000)
	}

	const onStopWatch = (num = 0) => {
		timeStore.endWatch(cubeStore.moveList.length + num)
		// 阶段3（复原/比赛）
		updateSeatStatus(5, 4)
		beginCubing()
	}

	//开始复原
	const beginCubing = () => {
		clearInterval(intervalTimer)
		times.value = 0
		intervalTimer = setInterval(() => {
			times.value = Date.now() - timeStore.gameStartTime;
			if (times.value > 1000 * 300) {
				clearInterval(intervalTimer)
				uni.showToast({
					title: '超时300秒，自动DNF',
					icon: 'none'
				})
				onGiveUp()
			}
		}, 5);
	}

	// 上报房间成绩
	const reportRoomResult = async () => {
		const rule = getCurrentRule()
		if (!seatInfo.value.id || !seatInfo.value.matchRoomId || !rule) return

		let score = undefined, time = undefined, step = undefined
		switch (rule.scoreModel) {
			case 1: // 时间短
			case 2: // 时间长
				time = timeStore.gameTime
				break
			case 7: // 步数短
			case 8: // 步数长
				step = timeStore.turn
				break
			case 5: // 得分少
			case 6: // 得分多
				score = 0 // 如有得分逻辑可替换
				break
			case 3: // 距离短
			case 4: // 距离长
				score = 0 // 如有距离逻辑可替换
				break
			default: // 不记分
				score = 0
				break
		}

		// 判断是否作弊
		let isDNF = false
		let cheatType = 0
		let status = 1 // 默认正常完成
		
		if (
			(timeStore.tps <= 6 && timeStore.turn <= 27) ||
			timeStore.gameTime <= 2000
		) {
			isDNF = true
			cheatType = 1 // 使用辅助工具
			status = 0 // 异常状态
		}

		try {
			await BattleAPI.updateRoomResult({
				matchRoomSeatId: seatInfo.value.id,
				matchRoomId: seatInfo.value.matchRoomId,
				matchScheduleId: seatInfo.value.matchScheduleId,  // 添加赛程ID
				matchRoomRuleId: rule.id,
				result: score,                              // 使用result字段而不是score
				time,
				step,
				status,                                     // 根据作弊检测结果设置状态
				cheatType,                                  // 根据作弊检测结果设置作弊类型
				matchPos: 0,
				createTime: Date.now(),                     // 添加创建时间
				updateTime: Date.now()                      // 添加更新时间
			})
			console.log('房间成绩上报成功')
		} catch (e) {
			console.error('房间成绩上报失败', e)
		}
	}


	// 计算赛程结果
	const reportScheduleResult = async () => {
	

		try {
			await BattleAPI.calcRoomResults({
				matchRoomId: seatInfo.value.matchRoomId
			})
			console.log('房间成绩上报成功')
		} catch (e) {
			console.error('房间成绩上报失败', e)
		}
	}


	// 复原完成
	const onComplete = () => {
		timeStore.endGame(cubeStore.moveList.length);
		clearInterval(intervalTimer);
		intervalTimer = undefined;

		// 标记当前规则为已完成
		completedRules.value.add(currentRuleIndex.value)

		// 上报房间成绩
		reportRoomResult()

		// 计算赛程结果
		reportScheduleResult()

		// 显示当前回合结果
		showResult()

		// 检查是否还有下一个规则
		if (currentRuleIndex.value < roomRules.value.length - 1) {
			// 还有下一个规则，自动进入下一回合
			setTimeout(() => {
				startNextRule()
				// 重置魔方状态，准备下一回合
				cubeReset()
				// 重置比赛数据
				timeStore.reset()
				// 阶段0（准备下一回合）
				updateSeatStatus(0, 0)
			}, 3000) // 3秒后自动开始下一回合
		} else {
			// 所有规则执行完成，结束比赛
			console.log('所有规则执行完成，比赛结束')
			// 阶段4（结果/比赛结束）
			updateSeatStatus(6, 5)
			uni.showToast({
				title: '恭喜完成所有回合！',
				icon: 'success'
			})
		}
		// WebSocket发送成绩上报消息（新协议）
		if (socketAdapter.value && connected.value) {
			const userId = userStore.userInfo?.id || `user-${Date.now()}`
			socketAdapter.value.sendRoomSeatOwnerStatusChange(
				userId,
				timeStore.turn || 0,
				timeStore.rotate || 0,
				timeStore.tps || 0,
				timeStore.smooth || 0,
				timeStore.currentTPS || 0,
				timeStore.progress || 100
			)
		}
	};

	// 显示结果
	const showResult = () => {
		timeStore.checkout(
			cubeStore.moveList,
			cubeStore.moveTimeList,
			cubeStore.model
		);

		// 判断是否作弊
		let isDNF = false
		if (
			(timeStore.tps <= 6 && timeStore.turn <= 27) ||
			timeStore.gameTime <= 2000
		) {
			uni.showToast({
				title: '检测到你本局存在违规行为，比赛成绩判定为DNF',
				icon: 'none'
			})
			isDNF = true
		}
		
		mCall('keep_screen_off')
	}

	// 丟步重设
	const resetCubeFates = () => {
		cubeGame.facelets.setFaceLetsInPlaying(cubeStore.cubeFace)
	}

	// 设置魔方面
	const setFace = (data) => {
		cubeStore.onFace(data)
		cubeGame.facelets.setFaceLetsInPlaying(data)
		const now = Date.now()
		if (now - faceLetsTime > 2000) {
			faceLetsTime = now
		}
	}

	// 更新席位状态
	const updateSeatStatus = async (status, event) => {
		if (!seatId.value) return
		
		try {
			console.log(`更新席位状态: status=${status}, event=${event}`)
			await BattleAPI.updateRoomSeatStatus({
				matchRoomSeatId: seatId.value,
				event: event
			})
			
			// 更新本地状态
			seatInfo.value.status = status
			seatInfo.value.event = event
			
			console.log('席位状态更新成功')
			// WebSocket发送席位状态变更消息（新协议）
			if (socketAdapter.value && connected.value) {
				socketAdapter.value.sendRoomSeatStatusChange(seatId.value, event, seatInfo.value.matchRoomId)
			}
		} catch (error) {
			console.error('更新席位状态失败:', error)
		}
	}

	// 比赛开始（打乱）
	const start = async () => {
		console.log('start')
		
		try {
			// 使用API生成打乱公式
			const result = await BattleAPI.cubeGenerateScramble({})
			if (result.code === 0 && result.data) {
				// 处理打乱公式数据，将^替换为'
				const scrambleData = result.data.replace(/\^/g, '\'')
				cube_generate_scramble.value = scrambleData
				console.log('生成的打乱公式:', cube_generate_scramble.value)
			} else {
				// 如果API失败，使用本地生成的简单打乱公式
				cube_generate_scramble.value = generateSimpleScramble()
				console.log('使用本地生成的打乱公式:', cube_generate_scramble.value)
			}
		} catch (error) {
			console.error('生成打乱公式失败，使用本地生成:', error)
			// 使用本地生成的简单打乱公式
			cube_generate_scramble.value = generateSimpleScramble()
			console.log('使用本地生成的打乱公式:', cube_generate_scramble.value)
		}
		
		times.value = 45

		//重置比赛数据
		timeStore.reset();
		timeStore.startScramble(cube_generate_scramble.value);
		
		// 阶段1（打乱/开始赛前准备）
		updateSeatStatus(3, 2)
		
		clearInterval(intervalTimer);
		// WebSocket发送席位状态变更消息（新协议）
		if (socketAdapter.value && connected.value) {
			socketAdapter.value.sendRoomSeatStatusChange(seatId.value, 2, seatInfo.value.matchRoomId)
		}
	}

	// 生成简单的打乱公式
	const generateSimpleScramble = () => {
		const faces = ['R', 'L', 'U', 'D', 'F', 'B']
		const modifiers = ['', "'", '2']
		const moves = []
		let lastFace = ''
		let secondLastFace = ''
		
		// 生成20步打乱公式
		for (let i = 0; i < 20; i++) {
			let face, modifier
			do {
				face = faces[Math.floor(Math.random() * faces.length)]
				modifier = modifiers[Math.floor(Math.random() * modifiers.length)]
			} while (face === lastFace || face === secondLastFace) // 避免连续相同面
			
			moves.push(face + modifier)
			secondLastFace = lastFace
			lastFace = face
		}
		
		return moves.join(' ')
	}

	// 设备信息
	const getEquipment = () => {
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 3,
			}
		})
	}
	
	// 电池电量
	const getBattery = () => {
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 8,
			}
		})
	}

	// 页面加载
	onLoad((options) => {
		if (options.seatId) {
			seatId.value = options.seatId
			fetchSeatInfo()
		}
	})

	onMounted(async () => {
		cubeGame = new cube3d()
		
		// 先注册mBus事件监听器（同步）
		mBus({
			ble_is_connected(res) {
				ble_is_connected.value = res.data
			},
			ble_has_permission(res) {
				ble_has_permission.value = res.data
			},
		
			// 接收转动魔方时的信息V2
			onReceiveJSONData(res) {
				console.log('onReceiveJSONData 被触发:', res)
				res = res.data ? res.data : res
				if (res) {
					switch (+res.protoId) {
						// 转动
						case 1:
							const name = CubeMap[res.formula]
							res.cubeName = name
							
							cubeStore.onMove(res)
							cubeMoves.value.push(name)
							cubeGame.transcube.trans(name)
							mCall('cube_get_facelets')
							VmCube.move(name)
							console.log('asString:', VmCube.asString())
							setFace(VmCube.asString())
							console.log('收到魔方转动数据', res)
							console.log('socketAdapter', socketAdapter.value, 'connected', connected.value)
							// WebSocket实时发送魔方转动消息
							if (socketAdapter.value && connected.value && res) {
								socketAdapter.value.sendCubeMove(
									res.cubeName, // move
									res.interval || 0, // interval
									res.step || 1,     // step
									res.rotate || 0,   // rotate
									res.modify || 0    // modify
								)
								console.log('已发送魔方转动消息')
							}
							// 检查魔方是否还原
							if ('UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB' == VmCube.asString()) {
								console.log('魔方已还原!')
								cubeStore.onResolved(true)
								if (timeStore.stage === 3) {
									onComplete();
									mCall('cube_get_facelets')
								}
							}
							// 观察中
							if (timeStore.stage === 2) {
								onStopWatch(-1)
							}
							
							// 左右转动下一把
							if ([0, 4].includes(timeStore.stage)) {
								if (cubeMoves.value.length > 1) {
									let last = cubeMoves.value[cubeMoves.value.length - 2]
									if (name + '\'' === last || name === last + '\'') {
										cubeMoves.value = []
									}
								}
							}
							break;
						// 魔方复原重置
						case 2:
							if (timeStore.stage === 3) {
								onComplete();
								mCall('cube_get_facelets')
							}
							cubeGame.facelets.setFaceLets('UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB')
						// 同步状态
						case 3:
							
							break;
						// 电池电量
						case 4:
							battery.value = res
							break;
					
						default:
							break;
					}
				}
			},
			cube_get_facelets(res) {
				console.log('cube_get_facelets', res)
				cubeStore.onFace(res.data)
				if (cubeGame) {
					cubeGame.facelets.setFaceLets(res.data)
				}
			},
			cube_solve_in(res) {
				console.log('cube_solve_in', res)
			},
			cube_is_solved(res) {
				console.log('cube_is_solved', res)
				cubeStore.onResolved(res.data)
			},

			cube_get_info(res) {
				// log(JSON.stringify(res))
			},
			sendJSONData(res) {
				// log(JSON.stringify(res))
			},
			cube_sync(res) {
				mCall('cube_get_facelets')
			},
			cube_generate_scramble(res) {
				console.log('cube_generate_scramble', res)
				if (res && res.data) {
					// 处理打乱公式数据
					const scrambleData = res.data.replace(/\^/g, '\'')
					cube_generate_scramble.value = scrambleData
					console.log('设置打乱公式:', cube_generate_scramble.value)
					
					// 自动开始倒计时
					if ([0, 4].includes(timeStore.stage)) {
						start()
					}
				}
			}
		})
		
		console.log('mBus事件监听器已注册')
		
		// 然后初始化WebSocket连接（异步）
		await initSocketAdapter()
	})

	onUnmounted(() => {
		clearInterval(intervalTimer);
		console.log('seat-detail页面卸载，保持全局WebSocket连接')
		// 不调用 socketAdapter.value.disconnect()，保持全局连接
		// 只清理页面相关的定时器或其他资源
	})
</script>

<style lang="scss" scoped>
	uni-button {
		margin: 0;
		margin-left: 30rpx;
	}

	.content {
		padding: 5%;
		counter-reset: list;
	}

	// 页面头部样式
	.page-header {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		margin-bottom: 30rpx;
		border-bottom: 1rpx solid #eee;
		
		.back-btn {
			background: none;
			border: none;
			color: #333;
			font-size: 28rpx;
			padding: 10rpx 20rpx;
			margin-right: 20rpx;
		}
		
		.page-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}

	// 席位信息样式
	.seat-info-section {
		margin-bottom: 30rpx;
		
		.card {
			.card-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				
				.title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
				
				.seat-status {
					padding: 8rpx 20rpx;
					border-radius: 20rpx;
					font-size: 24rpx;
					font-weight: bold;
					
					&.status-idle { background: #d4edda; color: #155724; }
					&.status-occupy { background: #cce5ff; color: #004085; }
					&.status-ready { background: #fff3cd; color: #856404; }
					&.status-prepare { background: #d1ecf1; color: #0c5460; }
					&.status-plan { background: #e2e3e5; color: #383d41; }
					&.status-matching { background: #d4edda; color: #155724; }
					&.status-end { background: #f8d7da; color: #721c24; }
					&.status-error { background: #f8d7da; color: #721c24; }
				}
			}
			
			.loading-container {
				text-align: center;
				padding: 40rpx;
				color: #666;
				
				.loading-spinner {
					width: 60rpx;
					height: 60rpx;
					border: 4rpx solid #f3f3f3;
					border-top: 4rpx solid #667eea;
					border-radius: 50%;
					animation: spin 1s linear infinite;
					margin: 0 auto 20rpx;
				}
			}
			
			.info-content {
				.info-row {
					display: flex;
					margin-bottom: 15rpx;
					font-size: 26rpx;
					
					.info-label {
						width: 160rpx;
						color: #666;
						font-weight: 500;
					}
					
					.info-value {
						flex: 1;
						color: #333;
					}
				}
			}
		}
	}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	@keyframes fadeIn {
		from { opacity: 0; transform: translateY(20rpx); }
		to { opacity: 1; transform: translateY(0); }
	}

	@keyframes slideIn {
		from { transform: translateX(-100%); }
		to { transform: translateX(0); }
	}

	.flex {
		display: flex;
		align-items: center;
	}

	.flexstart {
		justify-content: flex-start;
	}

	.card {
		margin: 20rpx 0;

		&:first-child {
			margin-top: 0;
		}

		button {
			height: 60rpx;
			line-height: 60rpx;
			font-size: 26rpx;
			
			&:disabled {
				opacity: 0.6;
				cursor: not-allowed;
			}
		}

		> .title {
			min-width: 280rpx;
			line-height: 1.4;
			font-size: 28rpx
		}
	}

	.blank {
		margin-top: 50rpx;
	}
	
	.cube-box {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 200px;
		height: 200px;
		margin: 30px auto;
		background-color: #eee;
		border-radius: 10px;
		
		.cube3d {
			width: 400px;
			height: 400px;
			transform: scale(0.5);
		}
	}

	code {
		display: block;
		width: 80%;
		margin: 10rpx 0;
		padding: 20rpx;
		border-radius: 5px;
		background-color: #f5f5f5;
		font-size: 24rpx;
		word-break: break-word;
	}

	.game-rule {
		margin-bottom: 30rpx;

		.title {
			margin-bottom: 10rpx;
			color: #666;
			font-size: 24rpx;
		}
	}

	.start-game {
		margin: 50rpx 0;
	}

	.card uni-button.btn {
		display: block;
		height: 40px;
		width: 90%;
		margin: 8px;
		border-radius: 40px;
		line-height: 40px;
		font-size: 17px;
		border: 1px solid rgba(0, 0, 0, 0.2);

		&:after {
			border: none;
		}
	}

	.result {
		.msg {
			margin-top: 10rpx;
			color: #333;
		}
	}
	
	.led {
		margin: 10rpx;
	}

	.timer {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		
		&.fixed {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 1000;
		}
	}

	.formulaDisplay {
		.formula-display {
			margin: 20rpx 0;
		}
	}

	// 房间规则样式
	.room-rules-section {
		margin-bottom: 30rpx;
		animation: fadeIn 0.5s ease-out;
		
		.card {
			.card-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				
				.title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
				
				.rule-progress {
					padding: 8rpx 20rpx;
					border-radius: 20rpx;
					font-size: 24rpx;
					font-weight: bold;
					background: #667eea;
					color: white;
				}
			}
			
			.loading-container {
				text-align: center;
				padding: 40rpx;
				color: #666;
				
				.loading-spinner {
					width: 60rpx;
					height: 60rpx;
					border: 4rpx solid #f3f3f3;
					border-top: 4rpx solid #667eea;
					border-radius: 50%;
					animation: spin 1s linear infinite;
					margin: 0 auto 20rpx;
				}
			}
			
			.rules-content {
				.current-rule {
					margin-bottom: 20rpx;
					padding: 20rpx;
					background: #f8f9fa;
					border-radius: 12rpx;
					border-left: 4rpx solid #667eea;
					
					.rule-title {
						font-size: 28rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 10rpx;
					}
					
					.rule-info {
						.rule-description {
							font-size: 26rpx;
							color: #666;
							margin-bottom: 15rpx;
						}
						
						.rule-details {
							.detail-item {
								display: flex;
								justify-content: space-between;
								margin-bottom: 8rpx;
								
								.detail-label {
									font-size: 24rpx;
									font-weight: 500;
									color: #666;
								}
								
								.detail-value {
									font-size: 24rpx;
									color: #333;
									font-weight: bold;
								}
							}
						}
					}
				}
				
				.rules-list {
					margin-bottom: 20rpx;
					
					.rules-title {
						font-size: 28rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 15rpx;
					}
					
					.rule-item {
						display: flex;
						align-items: center;
						padding: 15rpx;
						margin-bottom: 10rpx;
						border-radius: 8rpx;
						background: #fff;
						border: 1rpx solid #e9ecef;
						transition: all 0.3s ease;
						
						&.current {
							background: #e3f2fd;
							border-color: #2196f3;
						}
						
						&.completed {
							background: #f1f8e9;
							border-color: #4caf50;
						}
						
						.rule-number {
							width: 60rpx;
							height: 60rpx;
							border-radius: 50%;
							background: #667eea;
							color: white;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 24rpx;
							font-weight: bold;
							margin-right: 20rpx;
						}
						
						.rule-content {
							flex: 1;
							
							.rule-path {
								font-size: 26rpx;
								color: #333;
								font-weight: bold;
								margin-bottom: 5rpx;
							}
							
							.rule-meta {
								font-size: 22rpx;
								color: #666;
								
								.meta-item {
									margin-right: 15rpx;
								}
							}
						}
						
						.rule-status {
							font-size: 22rpx;
							font-weight: bold;
							
							.status-completed {
								color: #4caf50;
							}
							
							.status-current {
								color: #2196f3;
							}
							
							.status-pending {
								color: #9e9e9e;
							}
						}
					}
				}
				
				.rule-controls {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-top: 20rpx;
					border-top: 1rpx solid #e9ecef;
					
					.control-btn {
						padding: 12rpx 24rpx;
						border-radius: 20rpx;
						font-size: 24rpx;
						font-weight: bold;
						background: #667eea;
						color: white;
						border: none;
						
						&:disabled {
							opacity: 0.6;
							cursor: not-allowed;
							background: #ccc;
						}
					}
				}
			}
		}
	}
</style>